package com.gdufe.common.handler;

import com.gdufe.common.utils.R;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class MyExtendAuthenticationEntryPointHandler extends OAuth2AuthenticationEntryPoint {

    private final static Logger log = LoggerFactory.getLogger(MyExtendAuthenticationEntryPointHandler.class);

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        //获取异常信息
        Throwable cause = authException.getCause();

        //自定义返回内容
        R r = new R();
        r.put("code", 401);
        r.put("msg", authException.getMessage());
        r.put("data", null);

        if (cause instanceof OAuth2AccessDeniedException) {
            r.put("msg", "访问被拒绝");
        } else if (cause instanceof InvalidTokenException) {
            r.put("msg", "无效Token");
        } else if (authException instanceof InsufficientAuthenticationException) {
            r.put("msg", "未授权");
        } else {
            r.put("msg", "未知异常");
        }

        response.setStatus(HttpStatus.OK.value());
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        PrintWriter printWriter = response.getWriter();
        printWriter.append(new ObjectMapper().writeValueAsString(r));
    }
}
